package com.example.doc.controller;

import com.example.doc.core.utils.FileUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

@RestController
@RequestMapping("/file")
public class FileController {

//    @PostMapping("/product")
//    public void uploadProduct(MultipartFile file){
//        String filename = file.getOriginalFilename();
////        String resourcePath = FileUtils.getServerPath();
//        String filePath = "E:/data/";
////        File dest = new File(filePath + filename);
//        FileUtils.transferFile(file,filePath + filename);
////        System.out.println(filename);
//    }

    @PostMapping("/product")
    public void uploadProduct(MultipartFile[] files){
//        String filename = file.getOriginalFilename();
        String filePath = "E:/data/";
        for (int i =0;i<files.length;i++){
            String filename = files[i].getOriginalFilename();
            FileUtils.transferFile(files[i],filePath + filename);
        }
    }

    @GetMapping("/download")
    public void doDownload(HttpServletRequest request, HttpServletResponse response, String filepath, String filename){
        try {
            filepath = FileUtils.getServerPath() + filepath;
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition","attachment;fileName=" + FileUtils.setFileDownloadHeader(request,filename));
            FileUtils.writeBytes(filepath,response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}
